import React, { useState } from 'react';
import { Eye, EyeOff, Mail, Lock, User, Shield, ArrowRight } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import CloudIcon from '../components/CloudIcon';
import { authApi } from '@/services/api';
import { useNavigate } from 'react-router-dom';

const Login = () => {
  const navigate = useNavigate();
  const [showPassword, setShowPassword] = useState(false);
  const [loginData, setLoginData] = useState({
    username: '',
    password: '',
    rememberMe: false
  });
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');

  const handleLogin = async (e) => {
    e.preventDefault();
    setIsLoading(true);
    setError('');
    
    try {
      const response = await authApi.login({
        username: loginData.username,
        password: loginData.password
      });
      
      if (response.code === "200" && response.msg === "success" && response.data) {
        const { accessToken, refreshToken, expires } = response.data;
        
        const storage = loginData.rememberMe ? localStorage : sessionStorage;
        
        storage.setItem('authToken', accessToken);
        storage.setItem('refreshToken', refreshToken);
        storage.setItem('tokenExpires', expires.toString());
        
        if (response.data.userInfo) {
          storage.setItem('userInfo', JSON.stringify(response.data.userInfo));
        }
        
        console.log('登录成功:', {
          accessToken: accessToken.substring(0, 20) + '...',
          expires: new Date(expires).toLocaleString()
        });
        
        navigate('/');
      } else {
        throw new Error(response.msg || '登录失败');
      }
    } catch (error) {
      console.error('登录失败:', error);
      
      let errorMessage = '登录失败，请稍后重试';
      
      if (error.status === 401) {
        errorMessage = '用户名或密码错误';
      } else if (error.status === 403) {
        errorMessage = '账户已被锁定，请联系管理员';
      } else if (error.status === 429) {
        errorMessage = '登录尝试过于频繁，请稍后再试';
      } else if (error.message) {
        errorMessage = error.message;
      }
      
      setError(errorMessage);
    } finally {
      setIsLoading(false);
    }
  };

  const handleInputChange = (field, value) => {
    setLoginData(prev => ({ ...prev, [field]: value }));
    if (error) {
      setError('');
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-material-grey-50 to-material-grey-100 flex items-center justify-center px-8 py-4 relative overflow-hidden">
      {/* 背景装饰 */}
      <div className="absolute inset-0 overflow-hidden">
        <div className="absolute -top-40 -right-40 w-80 h-80 bg-material-grey-200/30 rounded-full blur-3xl"></div>
        <div className="absolute -bottom-40 -left-40 w-80 h-80 bg-material-grey-200/30 rounded-full blur-3xl"></div>
        <div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-96 h-96 bg-material-grey-200/20 rounded-full blur-3xl"></div>
      </div>

      {/* 登录卡片 */}
      <Card className="w-full max-w-md relative z-10 shadow-2xl border-0 bg-white/95 backdrop-blur-sm">
        <CardHeader className="text-center pb-6">
          {/* Logo和标题 */}
          <div className="flex flex-col items-center space-y-4">
            <div className="w-16 h-16 bg-gradient-to-br from-primary to-primary-600 rounded-2xl flex items-center justify-center shadow-lg">
              <CloudIcon className="w-10 h-10 text-yellow-400" />
            </div>
            <div>
              <CardTitle className="text-2xl font-bold text-material-grey-800">
                筋斗云
              </CardTitle>
              <p className="text-material-grey-600 text-sm mt-1">
                智能私有云盘系统
              </p>
            </div>
          </div>
        </CardHeader>

        <CardContent className="px-12">
          <form onSubmit={handleLogin} className="space-y-6">
            {/* 错误提示 */}
            {error && (
              <div className="p-3 bg-red-50 border border-red-200 rounded-lg">
                <div className="flex items-center space-x-2">
                  <Shield className="w-4 h-4 text-red-600" />
                  <span className="text-sm text-red-800">{error}</span>
                </div>
              </div>
            )}

            {/* 用户名输入 */}
            <div className="space-y-2">
              <Label htmlFor="username" className="text-material-grey-700 font-medium">
                用户名或邮箱
              </Label>
              <div className="relative">
                <User className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-material-grey-500" />
                <Input
                  id="username"
                  type="text"
                  value={loginData.username}
                  onChange={(e) => handleInputChange('username', e.target.value)}
                  placeholder="请输入用户名或邮箱"
                  className="pl-10 h-12 border-material-grey-300 focus:border-primary focus:ring-primary/20"
                  required
                  disabled={isLoading}
                />
              </div>
            </div>

            {/* 密码输入 */}
            <div className="space-y-2">
              <Label htmlFor="password" className="text-material-grey-700 font-medium">
                密码
              </Label>
              <div className="relative">
                <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-material-grey-500" />
                <Input
                  id="password"
                  type={showPassword ? 'text' : 'password'}
                  value={loginData.password}
                  onChange={(e) => handleInputChange('password', e.target.value)}
                  placeholder="请输入密码"
                  className="pl-10 pr-10 h-12 border-material-grey-300 focus:border-primary focus:ring-primary/20"
                  required
                  disabled={isLoading}
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3 top-1/2 transform -translate-y-1/2 text-material-grey-500 hover:text-material-grey-700 transition-colors"
                  disabled={isLoading}
                >
                  {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                </button>
              </div>
            </div>

            {/* 记住我和忘记密码 */}
            <div className="flex items-center justify-between">
              <div className="flex items-center space-x-2">
                <Checkbox
                  id="remember"
                  checked={loginData.rememberMe}
                  onCheckedChange={(checked) => handleInputChange('rememberMe', checked)}
                  disabled={isLoading}
                />
                <Label htmlFor="remember" className="text-sm text-material-grey-600 cursor-pointer">
                  记住我
                </Label>
              </div>
              <button
                type="button"
                className="text-sm text-material-grey-400 cursor-not-allowed"
                disabled={true}
              >
                忘记密码？
              </button>
            </div>

            {/* 登录按钮 */}
            <Button
              type="submit"
              disabled={isLoading || !loginData.username || !loginData.password}
              className="w-full h-12 bg-gradient-to-r from-primary to-primary-600 hover:from-primary-600 hover:to-primary-700 text-white font-medium shadow-lg hover:shadow-xl transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {isLoading ? (
                <>
                  <div className="w-4 h-4 mr-2 border-2 border-white border-t-transparent rounded-full animate-spin" />
                  登录中...
                </>
              ) : (
                <>
                  登录
                  <ArrowRight className="w-4 h-4 ml-2" />
                </>
              )}
            </Button>
          </form>

          {/* 其他登录方式 */}
          <div className="mt-8">
            <div className="relative">
              <div className="absolute inset-0 flex items-center">
                <div className="w-full border-t border-material-grey-200"></div>
              </div>
              <div className="relative flex justify-center text-sm">
                <span className="px-4 bg-white text-material-grey-500">或者</span>
              </div>
            </div>

            <div className="mt-6 grid grid-cols-2 gap-3">
              <Button 
                variant="outline" 
                className="h-12 border-material-grey-300 bg-material-grey-100 text-material-grey-400 cursor-not-allowed"
                disabled={true}
              >
                <Mail className="w-4 h-4 mr-2" />
                邮箱登录
              </Button>
              <Button 
                variant="outline" 
                className="h-12 border-material-grey-300 bg-material-grey-100 text-material-grey-400 cursor-not-allowed"
                disabled={true}
              >
                <Shield className="w-4 h-4 mr-2" />
                SSO登录
              </Button>
            </div>
          </div>

          {/* 注册链接 */}
          <div className="mt-8 text-center">
            <p className="text-sm text-material-grey-600">
              还没有账户？{' '}
              <button 
                className="text-material-grey-400 cursor-not-allowed"
                disabled={true}
              >
                立即注册
              </button>
            </p>
          </div>
        </CardContent>
      </Card>

      {/* 底部信息 */}
      <div className="absolute bottom-6 left-1/2 transform -translate-x-1/2 text-center text-material-grey-600 text-sm">
        <p>© 2024 筋斗云. 保留所有权利.</p>
        <p className="mt-1">安全 · 可靠 · 高效</p>
      </div>
    </div>
  );
};

export default Login;
